package com.tanger.auth.authorization.web;

import com.alibaba.fastjson.JSON;
import com.tanger.auth.event.LoginEvent;
import com.tanger.auth.mapper.AuthMapper;
import com.tanger.common.exception.AbstractController;
import com.tanger.common.redis.RedisConstants;
import com.tanger.common.redis.RedisUtil;
import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.TokenUtils;
import com.tanger.common.vo.UserDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制层
 */
@RestController
@RequestMapping("/tanger/oauth/authorize")
@Api(value = "账户认证",tags="账户认证")
public class AuthController extends AbstractController {

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private AuthMapper authMapper;
	@Autowired
	ConsumerTokenServices tokenServices;
	@Autowired
	private ApplicationEventPublisher publisher;

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@ApiOperation(value = "验证token")
	@PostMapping("/validataToken")
	public ActionResult validataToken(HttpServletRequest request) {
		try {
			//获取token
			String authHeaderValue = TokenUtils.ValidateToken(request);
			publisher.publishEvent(new LoginEvent("验证登录","USER-OPERATE",null,authHeaderValue));
			boolean isExist = redisUtil.hasKey(RedisConstants.BASE_TOKEN_PREFIX + authHeaderValue);
			if (!isExist) return ActionResult.buildResultError("Login expired. Please log in again");
			Object obj = redisUtil.get(RedisConstants.BASE_TOKEN_PREFIX + authHeaderValue);
			UserDetail user = JSON.parseObject(JSON.toJSONString(obj),UserDetail.class);
			return ActionResult.buildResultSuccess(user);//ActionResult.buildResultSuccess(authMapper.queryUserInfoByPhone(user.getMobile()));
		} catch (Exception e) {
			logger.error("ValiDate Failed:"+e.getMessage());
			return ActionResult.buildResultError(e.getMessage());
		}
	}

	/**
	 * @return
	 * @Description:退出登录
	 * @author Hchenbin.
	 * @date 2022年6月23日 下午4:13:11
	 * @version V1.0
	 */
	@ApiOperation(value = "退出登录")
	@PostMapping(value = "/loginOut")
	public ActionResult loginOut(HttpServletRequest request) {
		try {
			//获取token
			String authHeaderValue = TokenUtils.ValidateToken(request);
			if (tokenServices.revokeToken(authHeaderValue)){
				redisUtil.del(RedisConstants.BASE_TOKEN_PREFIX + authHeaderValue);
				return ActionResult.buildResultSuccess();
			}else return ActionResult.buildResultSuccess("Logout failed");
		} catch (Exception e) {
			logger.error("Logout Failed:"+e.getMessage());
			return ActionResult.buildResultError(e.getMessage());
		}
	}
}